﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Web.Configuration;
using System.Collections;
using System.Configuration.Provider;

namespace WorkNodeFramework
{
    public class DataService
    {
        static WorkNodeSection section;
        static DataProvider defaultProvider;
        static DataProviderCollection providers;

        static DataService()
        {
            LoadProviders();
        }

        public static DataProviderCollection Providers {
            get {
                return providers;
            }
        }
        public static DataProvider Provider {
            get {
                return defaultProvider;
            }
        }

        static void LoadProviders()
        {
            if(section ==null)
            {
                section = (WorkNodeSection)ConfigurationManager.GetSection(ConfigurationSectionName.WORK_NODE_SERVICE);
                if(section==null)
                    throw new ConfigurationErrorsException("Can't find the WorkNodeService section of the application config file");
            }

            providers = new DataProviderCollection();
            ProvidersHelper.InstantiateProviders(section.Providers, providers, typeof(DataProvider));

            defaultProvider = providers[section.DefaultProvider];

            if (defaultProvider == null && providers.Count > 0)
            {
                IEnumerator enumer = providers.GetEnumerator();
                enumer.MoveNext();
                defaultProvider = (DataProvider)enumer.Current;
                if (defaultProvider == null)
                    throw new ProviderException("No providers could be located in the WorkNodeService section of the application config file.");
            }
        }
    }
}
